package lerry.load;


import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.Function;

/**
 * ...
 * @author lerry
 */
class LoadTool {
	
	static var loader:Loader;
	static var dataloader:URLLoader;
	static var call: Dynamic-> Void;
	
	static var pool;
	static var tempkey:String;
	
	/**
	 * 调用此方法开始加载
	 * @param	path 资源路径
	 * @param	key 用于获取该资源的key
	 * @param	cb 加载完成后
	 */
	static public function load(path:String, key:Dynamic, cb: Dynamic-> Void):Void {
		if (pool == null) {
			pool = new Map ();
		}
		tempkey = key;
		var na = path.substring(path.lastIndexOf(".")+1, path.length);
		if (na == "jpg" || na == "png"||na=="swf") {
			loader = new Loader();
			loader.load(new URLRequest(path));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoadCom);
		}else {
			dataloader = new URLLoader();
			dataloader.load(new URLRequest(path));
			dataloader.dataFormat=URLLoaderDataFormat.TEXT;
			dataloader.addEventListener(Event.COMPLETE, onDataCom);
		}
		
		call=cb;
		
		
	}
	
	static  function onDataCom(e:Event):Void {
		dataloader.removeEventListener(Event.COMPLETE, onDataCom);
		if (call != null) call(null);
	}
	
	static function onLoadCom(e:Event):Void {
		loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadCom);
		pool.set(tempkey,loader.content);
		if (call != null) call(null);
	}
	/**
	 * 取得swf文件中的类
	 * @param	name 类名
	 * @return
	 */
	static public function getClass(name:String):Dynamic{
		var cl = loader.contentLoaderInfo.applicationDomain.getDefinition(name);
		return cl;
	}
	/**
	 * 取得swf文件中的类
	 * @param	name 类名
	 * @return
	 */
	static public function getClassInstance(name:String):Dynamic {
		var cl = loader.contentLoaderInfo.applicationDomain.getDefinition(name);
		var ins = Type.createEmptyInstance(cl);
		return ins;
	}
	/**
	 * 取得已加载的位图
	 * @param	key 
	 * @return
	 */
	static public function getBitmap(key:Dynamic):Bitmap {
		var bt = pool.get(key);
		return cast(bt,Bitmap);
	}
	/**
	 * 取得已加载的位图数据
	 * @param	key 
	 * @return
	 */
	static public function getBitmapData(key:Dynamic):BitmapData {
		var bt = pool.get(key);
		var b = cast(bt, Bitmap);
		return b.bitmapData;
	}
}